package com.cms.jdbc;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class StatementUpdate<E> {
	private Class<?> c;

	public StatementUpdate(Class<?> c) {
		this.c = c;
	}

	public int executeUpdate(Statement sta, String sql) {
		int res = 0;
		try {
			res = sta.executeUpdate(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}

	@SuppressWarnings("unchecked")
	public List<E> executeQuery(Statement sta, String sql) {
		List<E> list = new ArrayList<E>();
		Field[] declaredFields = c.getDeclaredFields();
		try {
			ResultSet res = sta.executeQuery(sql);
			while (res.next()) {
				Object obj= c.getConstructor().newInstance();
				for (Field field : declaredFields) {
					PropertyDescriptor pd = new PropertyDescriptor(field.getName(), c);
					Method wm = pd.getWriteMethod();
					wm.invoke((E) obj, ResMethodFactory.getMethod(field).invoke(res, field.getName()));
				}
				list.add((E) obj);
			}
			return list;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IntrospectionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return list;
	}

}
